#! /bin/bash

tar_dir_name="TD-Worker"
all_op_names=("ThreeNN" "Cumsum" "ReduceSum" "GlobalAvgPool" "Lerp" "Histogram" "AsStrided" "Tril" "Gelu" "Triu" 
              "Mish" "MishGrad" "Dawsn" "Xlogy" "eye")

function convert_to_underline() {
    local input_string="$1"
    if [ "$input_string" = "ThreeNN" ]; then
        input_string="ThreeNn"
    fi
    local output_array=($(echo "$input_string" | sed 's/\([A-Z]\)/\ \1/g'))

    local result=""
    for i in "${output_array[@]}"; do
        lower_temp=$(echo "${i%% }" | tr '[:upper:]' '[:lower:]')

        if [[ -n $result ]]; then
            result+="_"
        fi
        result+="${lower_temp}"
    done

    echo "${result}"
}

function compile_single_op() {
    local upper_op_name="$1"
    local lower_op_name="$(convert_to_underline $upper_op_name)"
    rm -rf ./$tar_dir_name/$upper_op_name
    mkdir ./$tar_dir_name/$upper_op_name

    cd ${upper_op_name}
 
    cp -f ./CMakePresets.json ../$tar_dir_name/$upper_op_name
    sed -i "s/ascend910b/ascend310b/g" ./CMakePresets.json
    sed -i "s/False/True/g" ./CMakePresets.json
    sed -i "s/ascend910b/ascend310b/g" ./op_host/${lower_op_name}.cpp

    ./build.sh

    cp ./build_out/custom_opp_ubuntu_aarch64.run ../$tar_dir_name/$upper_op_name/

    mv -f ../$tar_dir_name/$upper_op_name/CMakePresets.json ./
    sed -i "s/ascend310b/ascend910b/g" ./op_host/${lower_op_name}.cpp
    
    cd ..
}

if [ ! -d "$tar_dir_name" ]; then
    mkdir ./$tar_dir_name
fi

if [ -z "$1" ]; then
    for upper_op_name in "${all_op_names[@]}"; do
        compile_single_op "$upper_op_name"
    done
else
    compile_single_op "$1"
fi

